import { BaseUrl } from "@/api";
import { ApiSysCommonUpload } from "@/api/apis/sys_common";
import { useUserStore } from "@/stores/modules/user";
import { RespOk } from "@/constant/codes";
import { ElMessage } from "element-plus";
import { formUploadProps } from "@/components/FormCreate/interface/upload";
import { formatStaticUrl } from "@/utils/domain";

//默认的上传配置,isMultiple是否允许多文件上传
export const defaultUploadProps = (fileType: "image" | "file" = "file", isMultiple = false, MaxSizeMb = 15): formUploadProps => {
  const userStore = useUserStore();
  let acceptFile = fileType == "image" ? "image/*" : "*"; //允许的文件类型
  let listTypeStr: "picture-card" | "text" | "picture" = fileType == "image" ? "picture-card" : "text"; //允许的文件类型
  let limit = isMultiple ? 20 : 1; //最大长传数量

  return {

    listType: listTypeStr,
    uploadType: fileType,
    multiple: true, //多文件（图）上传
    limit: limit,
    action: BaseUrl + ApiSysCommonUpload,
    modalTitle: "预览",
    // accept: acceptFile,
    autoUpload: true,
    drag: true,
    headers: { Authorization: "Bearer " + userStore.token },
    beforeUpload: (file: any): boolean => {
      //console.log(file, " ---file");
      let sizeMB = file.size / (1024 * 1024);
      if (sizeMB > MaxSizeMb) {
        ElMessage({ type: "error", message: "上传文件:" + sizeMB + "MB,超过最大尺寸限制:" + MaxSizeMb + "MB" });
        return false;
      }
      //console.log(sizeMB, " ---sizeMB");
      return true;
    },
    onSuccess: (res, file, fileList) => {
      if (res.code == RespOk) {
        ElMessage({ type: "success", message: "上传成功" });
        file.url = res.data.replaceAll("./", "/"); //res.data 是文件路径
        //return res.data;
      } else {
        ElMessage({ type: "error", message: "加载失败数据失败" + res.msg });
      }
    },
    onError: function(err: any, file: any, fileList: any[]) {
      ElMessage({ type: "error", message: "upload onError" + err });
      console.log(err, " upload onError---err");
    }
  };
};
